//
//  MainWindowController.m
//  HiQ
//
//  Created by maxwell pang on 12-7-20.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "MainWindowController.h"
#import "AddNewFriendWindowController.h"
#import "AddNewFriendRequestWindowController.h"
#import "ImageAndTextCell.h"
#import "Buddy.h"
#import "BuddyGroup.h"
#import "BuddyListSource.h"
#import "BuddyListPacketProcess.h"
#import "BuddyStatusPacketProcess.h"
#import "PacketDispathCenter.h"
#import "HeartBeatPacketProcess.h"
#import "AddNewFriendCenter.h"
#import "MacrosDefine.h"
#import "ClusterObjects.h"

static MainWindowController *sharedMainWindowController;


@interface MainWindowController ()

@end

@implementation MainWindowController

@synthesize pairChatArray;
@synthesize clusterChatArray;


@synthesize exitDiscussion;
@synthesize buddySource;
@synthesize clusterSource;
@synthesize buddyOutlineView;
@synthesize clusterOutlineView;
@synthesize buddyListPacketProcess;
@synthesize buddyStatusPacketProcess;
@synthesize listenPortPacketProcess;
@synthesize myselfInfo;
@synthesize clusterListPacketCenter;
@synthesize listenSocket;
@synthesize fileWindowController;
@synthesize heartBeatPacketProcess;
@synthesize msgWindowController;
@synthesize addNewFriendWindowController;
@synthesize addNewFriendRequestWindowController;
@synthesize addNewFriendCenter;
@synthesize isAddNewFriendAccept;

- (id)initWithWindow:(NSWindow *)window
{
    self = [super initWithWindow:window];
    if (self) {
        // Initialization code here.
        bgImageName =@"NIL";
        sharedMainWindowController = self;
        buddyListPacketProcess = [[BuddyListPacketProcess alloc] init];
        buddyStatusPacketProcess = [[BuddyStatusPacketProcess alloc] init];
        clusterListPacketCenter = [[ClusterListPacketCenter alloc] init];
        listenPortPacketProcess = [[ListenPortPacketProcess alloc] init];
        heartBeatPacketProcess = [[HeartBeatPacketProcess alloc] init];
        addNewFriendCenter = [[AddNewFriendCenter alloc] init];
        exitDiscussion = [[ExitDiscussion alloc] init];      
        exitDiscussion.delegate = (id<ExitDiscussionDelegate>)self;
        
        pairChatArray = [[NSMutableArray alloc] init];
        clusterChatArray = [[NSMutableArray alloc] init];
        
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"defaults" ofType:@"plist"];  
        NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
        
        NSNumber *heartBeatTimeIntervalNum = [data objectForKey:@"HeartBeatTimeInterval"];
        heartBeatTimeInterval = [heartBeatTimeIntervalNum intValue];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeBackgroundImage:) name:ChangeBackgroundImageNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RefreshBuddyList:) name:ReloadBuddyListNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onFallLine:) name:OnFallLine object:nil];
    }
    
    return self;
}

/*- (BOOL)windowShouldClose:(id)sender
 {
 return FALSE;
 }*/

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:buddyStatusPacketProcess];
}

- (void)windowDidLoad
{
    [super windowDidLoad];
    
}

- (void) initWithBuddyInfo:(Buddy*)m
{
    myselfInfo = m;
    myselfInfo.onPhoto = [NSImage imageNamed:myselfInfo.photo];
    myselfInfo.offPhoto = GrayImageFromNSImageWithAlpha(myselfInfo.onPhoto);
    
    // 客户端的监听端口   代理根据需要设为其它   目前仅传文件一个需求，所以应将代理设成传文件的类的对象
    /*dispatch_queue_t socketQueue11 = dispatch_queue_create("socketQueue11", nil);
     listenSocket = [[GCDAsyncSocket alloc] initWithDelegate:buddyListPacketProcess delegateQueue:socketQueue11]; // 将 initWithDelegate 设为正确的代理
     NSError *error;
     [listenSocket acceptOnPort:0 error:&error];
     myselfInfo.listenPort = [listenSocket localPort];*/
    /*文件监听端口开启*/
    fileListenSocket = [[FileListenSocket alloc] init];
    discussion = [[NewDiscussionWindowController alloc] initWithWindowNibName:@"NewDiscussionWindowController"];
    
    [listenPortPacketProcess sendListenPortPacket];
    
    [buddyListPacketProcess onGetBuddyList];   // 发获取好友列表的包
    [clusterListPacketCenter onGetClusterList];  // 发获取群列表的包
    
    NSArray * itemArray = [[[self window]toolbar]items];
    [[itemArray objectAtIndex:1]setImage:[NSImage imageNamed: myselfInfo.photo]];
    [[itemArray objectAtIndex:1]setLabel:myselfInfo.buddyName];
}

-(void) awakeFromNib
{
    buddySource = [[BuddyListSource alloc] init];
    clusterSource = [[ClusterListSource alloc] init];
    [[[self window]contentView] addSubview:buddyView];
    [[[self window] contentView] setWantsLayer:YES];
    
    [[NSNotificationCenter defaultCenter] addObserver:buddyStatusPacketProcess selector:@selector(onOffLine:) name:OnOffLine object:nil];
    [[self window] setReleasedWhenClosed:NO];
    //    [[[self window]toolbar] setDisplayMode:NSToolbarDisplayModeIconOnly];
    
    //buddy列表
    NSTableColumn* column = [buddyOutlineView tableColumnWithIdentifier:@"BuddyList"];
	
	ImageAndTextCell* cell = [[ImageAndTextCell alloc] init];
	[column setDataCell: cell];
    
    [buddyOutlineView setDataSource:(id<NSOutlineViewDataSource>)buddySource];  // 设置 buddyList 的 data source
    [buddyOutlineView setDelegate:(id<NSOutlineViewDelegate>)self]; // 设置 buddyList 的 delegate
    [buddyOutlineView setAction:@selector(onClickBuddyOutlineItem:)];
    [buddyOutlineView setDoubleAction:@selector(onDoubleClickBuddyOutlineItem:)];
    
    //cluster列表
    NSTableColumn* groupColumn = [clusterOutlineView tableColumnWithIdentifier:@"ClusterList"];
	
	ImageAndTextCell* groupCell = [[ImageAndTextCell alloc] init];
	[groupColumn setDataCell: groupCell];
    
    [clusterOutlineView setDataSource:(id<NSOutlineViewDataSource>)clusterSource];  // 设置 ClusterList 的 data source
    [clusterOutlineView setDelegate:(id<NSOutlineViewDelegate>)self]; // 设置 buddyList 的 delegate
    [clusterOutlineView setAction:@selector(onClickClusterOutlineItem:)];
    [clusterOutlineView setDoubleAction:@selector(onDoubleClickClusterOutlineItem:)];
    //    [clusterOutlineView onGetBuddyList];   // 发获取好友列表的包
    
    //读取背景图片配置
    bgimgs = [[[NSUserDefaults standardUserDefaults] stringForKey:@"BGIMAGES"] componentsSeparatedByString:@"/"];
    
    // 设置心跳间隔
    heartBeatTimer = [NSTimer scheduledTimerWithTimeInterval:heartBeatTimeInterval target:heartBeatPacketProcess selector:@selector(onHeartBeatTimeIntervalReach:) userInfo:nil repeats:YES];
}

- (BOOL)outlineView:(NSOutlineView *)outlineView shouldEditTableColumn:(NSTableColumn *)tableColumn item:(id)item
{
    return NO;
}

- (void)outlineView:(NSOutlineView*)olv willDisplayCell:(NSCell*)cell forTableColumn:(NSTableColumn*)tableColumn item:(id)item
{
    if ([[tableColumn identifier] isEqualToString: @"BuddyList"])
	{
        if([item isKindOfClass:[Buddy class]])
        {
            NSMutableString *buddyName = [[NSMutableString alloc] initWithString:((Buddy*)item)->buddyName];
            NSColor *txtColor;
            if (((Buddy*)item)->status == BUDDY_STATUS_ONLINE)
            {
                [(ImageAndTextCell*)cell setImage: ((Buddy*)item)->onPhoto];
                txtColor = [NSColor blackColor];
            }
            else
            {
                [(ImageAndTextCell*)cell setImage: ((Buddy*)item)->offPhoto];
                //字体为灰
                txtColor = [NSColor colorWithDeviceRed:(161/255.0) green:(161/255.0) blue:(161/255.0) alpha:1.0];
            }
            [(ImageAndTextCell*)cell setStringValue:buddyName];
            
            NSFont *txtFont = [NSFont boldSystemFontOfSize:13];
            NSDictionary *txtDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                     txtFont, NSFontAttributeName, txtColor, NSForegroundColorAttributeName, nil];
            NSAttributedString *attrStr = [[NSAttributedString alloc]
                                           initWithString:buddyName attributes:txtDict];
            [(ImageAndTextCell*)cell setAttributedStringValue:attrStr];
        }
        
        if([item isKindOfClass:[BuddyGroup class]])
        {
            [(ImageAndTextCell*)cell setImage: nil];
        }
        
    }
    if ([[tableColumn identifier] isEqualToString:@"ClusterList"]) {
        if([item isKindOfClass:[Cluster class]])
        {
            [(ImageAndTextCell*)cell setImage:[NSImage imageNamed:((Cluster*)item)->photo]];
            [(ImageAndTextCell*)cell setStringValue:((Cluster*)item)->clusterName];
        }
        
        if([item isKindOfClass:[ClusterGroup class]])
        {
            [(ImageAndTextCell*)cell setImage:nil];
        }
    }
}

#pragma mark -
#pragma mark on/off notification

- (void) RefreshBuddyList:(NSNotification*)notification
{
    NSMutableArray *buddyGroupArray = [buddySource buddyGroupArray];
    for (BuddyGroup *bg in buddyGroupArray) {
        NSInteger end = [bg.buddyList count]-1;
        NSInteger start = 0;
        while(start <= end) {
            NSInteger online = -1;
            NSInteger offline = end + 1;
            //正序查找不在线的
            for (NSInteger i = start; i<=end; i++) {
                Buddy *b = [bg.buddyList objectAtIndex:i];
                //转换灰度头像
                b.onPhoto = [NSImage imageNamed:b.photo];
                b.offPhoto = GrayImageFromNSImageWithAlpha(b.onPhoto);
                
                if (b.status != BUDDY_STATUS_ONLINE) {
                    offline = i;
                    break;
                }
            }
            //倒序查找在线的
            for (NSInteger j = end; j>offline; j--) {
                Buddy *end_b = [bg.buddyList objectAtIndex:j];
                //转换灰度头像
                end_b.onPhoto = [NSImage imageNamed:end_b.photo];
                end_b.offPhoto = GrayImageFromNSImageWithAlpha(end_b.onPhoto);
                if (end_b.status == BUDDY_STATUS_ONLINE) {
                    online = j;
                    break;
                }
            }
            
            if ((offline<=end)&&(online>=0)) {
                //交换位置
                [bg.buddyList exchangeObjectAtIndex:offline withObjectAtIndex:online];
            }
            
            //更新搜索位置
            start = offline + 1;
            end = online - 1;
        }   
    } 
}

#pragma mark -
#pragma mark buddyList View

- (void)onClickBuddyOutlineItem:(id)sender
{
    // 展开或收起好友列表
    id selectedItem = [buddyOutlineView itemAtRow:[sender clickedRow]];
    if(selectedItem == nil)
        return;
    if(![buddyOutlineView isExpandable:selectedItem])
        return;
    if([buddyOutlineView isItemExpanded:selectedItem])
        [buddyOutlineView collapseItem:selectedItem];
    else
        [buddyOutlineView expandItem:selectedItem];
}

- (void)onDoubleClickBuddyOutlineItem:(id)sender
{
    // 双击好友，打开聊天窗口
    id selectedItem = [buddyOutlineView itemAtRow:[sender clickedRow]];
    if(selectedItem == nil)
        return;
    if([buddyOutlineView isExpandable:selectedItem])
        return;
    
    for (NSUInteger i = 0; i < [pairChatArray count]; ++i) {
        if ([selectedItem buddyQQ] == [[[pairChatArray objectAtIndex:i] peerBuddy] buddyQQ]) {
            [self showChatWindow:i];
            return;
        }
    }
    
    [self openPairChatWindow:selectedItem];
    for (NSUInteger i = 0; i < [pairChatArray count]; ++i) {
        if ([selectedItem buddyQQ] == [[[pairChatArray objectAtIndex:i] peerBuddy] buddyQQ]) {
            [self showChatWindow:i];
            return;            
        }
    }
}

- (void)onClickClusterOutlineItem:(id)sender
{
    // 展开或收起好友列表
    id selectedItem = [clusterOutlineView itemAtRow:[sender clickedRow]];
    if(selectedItem == nil)
        return;
    if(![clusterOutlineView isExpandable:selectedItem])
        return;
    if([clusterOutlineView isItemExpanded:selectedItem])
        [clusterOutlineView collapseItem:selectedItem];
    else
        [clusterOutlineView expandItem:selectedItem];
}

- (void)onDoubleClickClusterOutlineItem:(id)sender
{
    //打开群聊窗口
    id selectedItem = [clusterOutlineView itemAtRow:[sender clickedRow]];
    if(selectedItem == nil)
        return;
    if([clusterOutlineView isExpandable:selectedItem])
        return;
    
    for (NSUInteger i = 0; i < [clusterChatArray count]; ++i) {
        if (selectedItem == [[[clusterChatArray objectAtIndex:i] clusterChatSource] _cluster]) {
            [self showClusterChatWindow:i];
            return;
        }
    }
    
    [self openClusterChatWindow:selectedItem];
    for (NSUInteger i = 0; i < [clusterChatArray count]; ++i) {
        if (selectedItem == [[[clusterChatArray objectAtIndex:i] clusterChatSource] _cluster]) {
            [self showClusterChatWindow:i];
            return;
        }
    }
}

- (void) prepareWindowForGrowl:(NSInteger)pQ chatMessage:(NSString*)chatMsg
{
    for (BuddyGroup *group in buddySource.buddyGroupArray) {
        for (Buddy* buddy in group->buddyList) {
            if (buddy.buddyQQ == pQ) {
                [self openPairChatWindow:buddy];
                return;
            }
        }
    }
}

-(void) prepareClusterWindowForGrowl:(NSInteger)groupId chatMessage:(NSString *)chatMsg
{
    for (ClusterGroup *group in clusterSource.clusterGroupArray) {
        for (Cluster *cluster in group->clusterList) {
            if (groupId == cluster.clusterId) {
                [self openClusterChatWindow:cluster];
                return;
            }
        }
    }
}

- (void)prepareAddNewFriendWindowForGrowl:(NSInteger)fromId to:(NSInteger)toId
{
    addNewFriendRequestWindowController = [[AddNewFriendRequestWindowController alloc] initWithWindowNibName:@"AddNewFriendRequestWindowController"];
    addNewFriendRequestWindowController->fromId = fromId;
    addNewFriendRequestWindowController->toId = toId;
}

- (void)prepareIsAcceptAddNewFriendWindowForGrowl:(NSInteger)isAccept fromId:(NSInteger)fromId to:(NSInteger)toId
{
    isAddNewFriendAccept = [[NSAlert alloc] init];
    [isAddNewFriendAccept addButtonWithTitle:NSLocalizedString(@"确定", nil)];
    [isAddNewFriendAccept setMessageText:NSLocalizedString(@"添加好友",nil)];
    NSString *informativeText;
    if (isAccept == REPLY_ACCEPT)
    {
        informativeText = [[NSString alloc] initWithFormat:NSLocalizedString(@"%ld 同意了您的添加请求", nil), toId];
    }
    else if (isAccept == REPLY_REJECT)
    {
        informativeText = [[NSString alloc] initWithFormat:NSLocalizedString(@"%ld 拒绝了您的添加请求", nil), toId];
    }
    else if (isAccept == REPLY_OFFLINE)
    {
        informativeText = [[NSString alloc] initWithFormat:NSLocalizedString(@"%ld 不在线", nil), toId];
    }
    [isAddNewFriendAccept setInformativeText:informativeText];
    [isAddNewFriendAccept setAlertStyle:NSWarningAlertStyle];
}

- (void) showChatWindow:(NSUInteger) index
{
    PairChatWindowController *pair = [pairChatArray objectAtIndex:index];
    [pair showWindow:self];
    [pair displayChatMessage:nil nameFlag:PEERNAME];
    [pair setNamePohtoAndBgImage:bgImageName];
    pair.isShow = YES;
}

-(void) showClusterChatWindow:(NSUInteger) index
{
    ClusterChatWindowController *clusterChat = [clusterChatArray objectAtIndex:index];
    [clusterChat showWindow:self];
    [clusterChat displayChatMessage:nil Name:nil];
    [clusterChat setNamePohtoAndBgImage:bgImageName];
    clusterChat.isShow = YES;
}

- (void)showNewFriendRequest
{
    [addNewFriendRequestWindowController showWindow:self];
    
    [NSApp activateIgnoringOtherApps:YES];
    [addNewFriendRequestWindowController.window makeKeyAndOrderFront:self];
}

- (void)showIsAcceptNewFriendRequest
{
    [isAddNewFriendAccept beginSheetModalForWindow:nil modalDelegate:nil didEndSelector:nil contextInfo:nil];
    [isAddNewFriendAccept.window makeKeyAndOrderFront:self];
}

-(void) openPairChatWindow:(Buddy *)selectedItem
{
    // 打开好友聊天窗口
    PairChatWindowController *pair = [[PairChatWindowController alloc]initWithWindowNibName:@"PairChatWindowController"];
    [pair initPairChat:selectedItem selfBuddyInfo:myselfInfo];
    pair.isShow = NO;
}

-(void)openClusterChatWindow:(Cluster*)clusterInfo
{
    ClusterChatWindowController *clusterChat = [[ClusterChatWindowController alloc]initWithWindowNibName:@"ClusterChatWindowController"];    
    [clusterChat initClusterChat:clusterInfo];
    clusterChat.isShow = NO;
}

- (IBAction)onAddNewFriend:(id)sender
{
    addNewFriendWindowController = [[AddNewFriendWindowController alloc] initWithWindowNibName:@"AddNewFriendWindowController"];
    [addNewFriendWindowController showWindow:self];
    
    [addNewFriendWindowController.window makeKeyAndOrderFront:self];
}

-(IBAction)changeBackground:(id)sender
{
    NSString *bgimg;
    NSUInteger max = [bgimgs count];
    skinNum = (skinNum+1)%(max+1);
    if (skinNum == max) {
        bgimg = @"NIL";
    }
    else
    {
        bgimg = [bgimgs objectAtIndex:skinNum];
    }
    NSDictionary *uInfo = [NSDictionary dictionaryWithObject:bgimg forKey:@"img"];
    //换肤通知
    [[NSNotificationCenter defaultCenter] postNotificationName:ChangeBackgroundImageNotification object:nil userInfo:uInfo];
    
    //    self.window = mainHUDWindow;
    //    [self showWindow:self];
}

- (void) changeBackgroundImage:(NSNotification*)notification
{
    [buddyOutlineView clearBackgroundImage];
    [clusterOutlineView clearBackgroundImage];
    [self.window setBackgroundColor:nil];
    
    bgImageName = [[notification userInfo] objectForKey:@"img"];
    if (bgImageName != @"NIL") {
        NSImage *bgImage = [NSImage imageNamed:bgImageName];
        [buddyOutlineView setBackgroundImage:bgImage];
        [clusterOutlineView setBackgroundImage:bgImage];
        [self.window setBackgroundColor:[NSColor colorWithPatternImage:[NSImage imageNamed:bgImageName]]];
    }
}

#pragma mark -
#pragma mark clusterList View

-(void) onChangeLogin
{
    [heartBeatTimer invalidate];
    
    NSMutableArray *buddyGroupArray = [buddySource buddyGroupArray];
    if ([buddyGroupArray count] > 0)
    {
        BuddyGroup *firstGroup = [buddyGroupArray objectAtIndex:0];
        for (Buddy *buddy in firstGroup->buddyList)
        {
            buddy->status = BUDDY_STATUS_OFFLINE;
        }
        [buddyOutlineView reloadData];
    }
    
    NSAlert *alert = [[NSAlert alloc] init];
    [alert addButtonWithTitle:NSLocalizedString(@"确定", nil)];
    [alert setMessageText:NSLocalizedString(@"该账号在别处登陆,被迫下线",nil)];
    [alert setAlertStyle:NSWarningAlertStyle];
    [alert beginSheetModalForWindow:nil modalDelegate:nil didEndSelector:nil contextInfo:nil];
}

-(void) onExitDiscussionInfo:(NSUInteger) groupId UserID:(NSUInteger) userId
{
    for (ClusterChatWindowController *controller in clusterChatArray) {
        if ([[[controller clusterChatSource] _cluster] clusterId] == groupId) 
        {
            for (Buddy *buddy in [[[controller clusterChatSource] _cluster] memberList]) {
                if ([buddy buddyQQ] == userId) {
                    [[[[controller clusterChatSource] _cluster] memberList] removeObject:buddy];
                    [[controller tableClusterMember] reloadData];
                    return;
                }
            }
        }
    }
}


-(IBAction)onExitDiscussion:(id)sender
{
    NSInteger row = [clusterOutlineView selectedRow]-1;
    
    NSMutableArray *clusterGroupArray = [clusterSource clusterGroupArray];
    ClusterGroup *group = [clusterGroupArray objectAtIndex:0];
    if (row < -1 || row > [group->clusterList count] ) {
        return;
    }
    Cluster *cluster = [group->clusterList objectAtIndex:row];
    
    NSUInteger groupId = [cluster clusterId];
    NSString *groupName = [cluster clusterName];
    
    //弹出提示框
    NSString *groupInfo = [NSString stringWithFormat:NSLocalizedString(@"已经退出群: %@ ",nil),groupName];    
    NSAlert *alert = [[NSAlert alloc] init];
    [alert addButtonWithTitle:NSLocalizedString(@"确定", nil)];
    [alert setMessageText:groupInfo];
    [alert setAlertStyle:NSWarningAlertStyle];
    [alert beginSheetModalForWindow:nil modalDelegate:nil didEndSelector:nil contextInfo:nil];
    
    
    NSUInteger userId = [myselfInfo buddyQQ];
    [exitDiscussion onExitDiscussion:groupId UserID:userId];
    
    for (ClusterChatWindowController *controller in clusterChatArray) {
        if ([[[controller clusterChatSource] _cluster] clusterId] == groupId) 
        {
            [controller close];
        }
    }
    
    for (Cluster *pc in group->clusterList) {
        if(pc == cluster)
        {
            [group->clusterList removeObject:cluster];
            [clusterOutlineView reloadData];
            break;
        }
    }
}

-(void) onNewDiscussionCreate
{
    [clusterOutlineView reloadData];
}


-(IBAction)onNewDiscussion:(id)sender
{
    discussion = [[NewDiscussionWindowController alloc] initWithWindowNibName:@"NewDiscussionWindowController"];
    [discussion showWindow:self];
}


#pragma mark -
#pragma mark toolbar

-(NSView *)viewForTag:(NSInteger)tag
{
    NSView *view = nil;
    switch (tag) {
        case 0:
            view = buddyView;
            break;
        case 1:
            view = clusterView;
            break;
        default:
            view = buddyView;
            break;
    }
    return view;
}

//-(BOOL)validateToolbarItem:(NSToolbarItem *)theItem
//{
//    if ([theItem tag] == 2) {
//        return YES;
//    }
//    if ([theItem tag] == currentTag) {
//        return YES;
//    }
//    else {
//        return NO;
//    }
//}

-(IBAction)switchView:(id)sender
{
    NSInteger tag = [sender tag];
    if (tag == 2) {
        return;
    }
    NSView *view = [self viewForTag:tag];
    NSView *previousView = [self viewForTag:currentTag];
    currentTag = tag;
    
    NSArray *items = [toolbar items];
    for (int i = 0; i< [ items count]; i++) {
        NSToolbarItem * item = [items objectAtIndex:i];
        if ([item tag] == 2) {
            continue;
        }
        if ([item tag] == tag) {
            continue;
        }
        [item setImage:[NSImage imageNamed:[NSString stringWithFormat:@"group%lu.png",[item tag]]]];
    }
    [(NSToolbarItem *)sender setImage:[NSImage imageNamed:[NSString stringWithFormat:@"group%lu_Down.png", tag]]];
    [NSAnimationContext beginGrouping];
    [[[[self window] contentView] animator] replaceSubview:previousView with:view];
	[NSAnimationContext endGrouping];
    
    
}

#pragma mark -
#pragma mark image grey


CGImageRef CGImageRefCopyFromNSImage(NSImage* image)
{
	NSSize size = [image size];
	if(size.width == 0 || size.height ==0)
	{
        NSBitmapImageRep * rep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];
		NSSize imgSize = NSMakeSize([rep pixelsWide],[rep pixelsHigh]);
		[image setSize:imgSize];
	}
    
    NSData * imageData = [image TIFFRepresentation];
    CGImageRef imageRef = nil;
    if(imageData)
    {
        CGImageSourceRef imageSource = 	CGImageSourceCreateWithData((__bridge CFDataRef)(imageData),  NULL);	 //need release
        imageRef = CGImageSourceCreateImageAtIndex( imageSource, 0, NULL);   //need release by caller
		
		CFRelease(imageSource);
    }
	
    return imageRef;
	
}

CGImageRef SourceDataImageRefCopyFromCGImageRef(CGImageRef img)
{
	CGColorSpaceRef colorspace = NULL;
	CGContextRef context = NULL;
	
	colorspace = CGColorSpaceCreateDeviceGray();  //need release
	size_t pixelsWide = CGImageGetWidth(img);
	size_t pixelsHigh = CGImageGetHeight(img);
	//int	bitmapBytesPerRow = pixelsWide * (enableAlaph ? 4 : 1);
	size_t bitmapBytesPerRow = pixelsWide;
	
	context = CGBitmapContextCreate(NULL,
									pixelsWide,
									pixelsHigh,
									8,
									bitmapBytesPerRow,
									colorspace,
									kCGImageAlphaNone);  //need release
	
	CGRect rect = {{0, 0}, {pixelsWide, pixelsHigh}};
	CGContextDrawImage(context, rect, img);
	
	CGImageRef test = CGBitmapContextCreateImage(context) ;  //need release out
	
	CGColorSpaceRelease(colorspace);
	CGContextRelease(context);
	return test;
}

CGImageRef AlphaDataImageRefCopyFromCGImageRef(CGImageRef img)
{
	CGContextRef context = NULL;
	
	size_t pixelsWide = CGImageGetWidth(img);
	size_t pixelsHigh = CGImageGetHeight(img);
	//int	bitmapBytesPerRow = pixelsWide * (enableAlaph ? 4 : 1);
	size_t bitmapBytesPerRow = pixelsWide ;
	
	context = CGBitmapContextCreate(NULL,
									pixelsWide,
									pixelsHigh,
									8,
									bitmapBytesPerRow,
									NULL,
									kCGImageAlphaOnly);  //need release
	
	CGRect rect = {{0, 0}, {pixelsWide, pixelsHigh}};
	CGContextDrawImage(context, rect, img);
	
	CGImageRef test = CGBitmapContextCreateImage(context) ;  //need release out
	CGContextRelease(context);
	return test;
}


NSImage* GrayImageFromNSImageWithAlpha(NSImage*image)
{
	CGImageRef inImage = CGImageRefCopyFromNSImage(image);  //need release
	CGImageRef imgSourceData = SourceDataImageRefCopyFromCGImageRef(inImage);//need release
	CGImageRef imgAlphaData = AlphaDataImageRefCopyFromCGImageRef(inImage);//need release
	
	CGImageRef imgResultData = CGImageCreateWithMask(imgSourceData, imgAlphaData);//need release
    
	NSImage *imgResult = nsImageFromCGImageRef(imgResultData);
	
	CGImageRelease(inImage);
	CGImageRelease(imgSourceData);
	CGImageRelease(imgAlphaData);
	CGImageRelease(imgResultData);
	
	return imgResult;
}

NSImage* nsImageFromCGImageRef(CGImageRef image)
{
    NSRect imageRect = NSMakeRect(0.0, 0.0, 0.0, 0.0);
    CGContextRef imageContext = nil;
    NSImage* newImage = nil;
    // Get the image dimensions.
    imageRect.size.height = CGImageGetHeight(image);
    imageRect.size.width = CGImageGetWidth(image);
    // Create a new image to receive the Quartz image data.
	if(imageRect.size.height ==0 ||imageRect.size.width ==0)
	{
		NSLog(@"nsImageFromCGImageRef should not be here!!!,CGImageRef is %@",image);
	}
    newImage = [[NSImage alloc] initWithSize:imageRect.size];
    [newImage lockFocus];
    // Get the Quartz context and draw.
    imageContext = (CGContextRef)[[NSGraphicsContext currentContext]
								  graphicsPort];
    CGContextDrawImage(imageContext, *(CGRect*)&imageRect, image);
    [newImage unlockFocus];
    return newImage;
}


#pragma mark -
#pragma mark utils

// 掉线弹窗
- (void) onFallLine:(NSNotification *)notification
{
    [heartBeatTimer invalidate];
    
    NSMutableArray *buddyGroupArray = [buddySource buddyGroupArray];
    if ([buddyGroupArray count] > 0)
    {
        BuddyGroup *firstGroup = [buddyGroupArray objectAtIndex:0];
        for (Buddy *buddy in firstGroup->buddyList)
        {
            buddy->status = BUDDY_STATUS_OFFLINE;
        }
        [buddyOutlineView reloadData];
    }
    
    NSAlert *alert = [[NSAlert alloc] init];
    [alert addButtonWithTitle:NSLocalizedString(@"确定", nil)];
    [alert setMessageText:NSLocalizedString(@"与服务器断开连接",nil)];
    [alert setAlertStyle:NSWarningAlertStyle];
    [alert beginSheetModalForWindow:nil modalDelegate:nil didEndSelector:nil contextInfo:nil];
}

+(id)sharedMainWindowController
{
    return sharedMainWindowController;
}

+(id) shareMyselfInfo
{
    return sharedMainWindowController->myselfInfo;
}

@end
